var gbl_pause_sec = 3.5;
var gbl_fade_sec = 1;
var gbl_fade_fms = 30; /* Milliseconds per fade frame */

function init_gallery(id) {
	var gallery = new Object;
	gallery.dom = document.getElementById(id);
	var imgs = new Array;
	gallery.imgs = imgs;
	for (var node = gallery.dom.firstChild; node; node = node.nextSibling) {
		if (node.nodeType == 1 /* Node.ELEMENT_NODE */) {
			//node.style.position = 'absolute';
			//node.style.top = 0;
			node.style.zIndex = 0;
			set_opacity(node, 0);
			node.style.visibility = 'visible';
			imgs.push(node);
		}
	}
	if (gallery.imgs.length <= 0)
		return;

	/* Navigation button */
	var nav = document.createElement('div');
	nav.appendChild(document.createTextNode('next'));
	nav.style.position = 'absolute';
	nav.style.top = 0;
	nav.style.right = 0;
	nav.style.zIndex = 3;
	nav.style.padding = '0.2em 1em 0.2em 1em';
	nav.style.backgroundColor = '#fff';
	nav.style.fontVariant = 'small-caps';
	nav.onclick = function() {
		if (gallery.op >= 100) {
			window.clearTimeout(gallery.timerID);
			slideshow_fade(gallery);
		}
	}
	gallery.dom.appendChild(nav);
	
	imgs[0].style.zIndex = 1;
	set_opacity(imgs[0], 100);
	set_opacity(imgs[1 % imgs.length], 100);
	gallery.target = 0;
	gallery.op = 100;
	gallery.timerID = window.setTimeout(function() {
			slideshow_fade(gallery);
		}, gbl_pause_sec * 1000);
}

function slideshow_fade(gallery) {
	var i = gallery.target;
	var imgs = gallery.imgs;
	if (gallery.op > 0) {
		gallery.op -= 100 / (gbl_fade_fms * gbl_fade_sec);
		set_opacity(imgs[i], gallery.op);
		gallery.timerID = window.setTimeout(function() { slideshow_fade(gallery); }, gbl_fade_fms);
	} else {
		imgs[i].style.zIndex = 0;
		i = (i + 1) % imgs.length;
		imgs[i].style.zIndex = 1;
		set_opacity(imgs[(i + 1) % imgs.length], 100);
		gallery.target = i;
		gallery.op = 100;
		gallery.timerID = window.setTimeout(function() {
				slideshow_fade(gallery);
			}, gbl_pause_sec * 1000);
	}
}

function set_opacity(obj, opacity) {
	opacity = (opacity == 100) ? 99.999 : opacity;
	obj.style.filter = 'alpha(opacity:' + opacity + ')'; /* IE */
	opacity /= 100;
	obj.style.KHTMLOpacity = opacity; /* Safari (< v1.2), Konqueror */
	obj.style.MozOpacity = opacity; /* Older Mozilla and Firefox */
	obj.style.opacity = opacity; /* Safari (v1.2+), newer Firefox and Mozilla, CSS3 */
}
